package erfgame.core.memory;

import java.util.logging.Logger;

public final class InMemoryObject<Type> {
	
	private static final Logger log = Logger.getLogger(InMemoryObject.class.getName());
	
	private Type value;
	private MemoryPool<Type> pool;
	private int referenceCount;
	
	public InMemoryObject( MemoryPool<Type> pool, Type value ) {
		this.pool = pool;
		this.value = value;
	}
	
	public Type getValue() {
		return value;
	}
	
	public Pointer<Type> createPointer() {
		referenceCount++;
//		log.info("pointer to "+value+" has "+referenceCount+" references");
		return new Pointer<Type>( this );
	}
	
	public void releasePointer( Pointer<Type> pointer ) {
		referenceCount--;
//		log.info("pointer to "+value+" has "+referenceCount+" references");
		if( referenceCount == 0 ) {
			// this memory is free, put back in the pool
			pool.add( this );
		}
	}
}
